// pages/read/read.js
const db = wx.cloud.database();
const app = getApp();
const chapterContent = "contents";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    downloadNext: false,
    catcheList: [],
    top: 0,
    showLast: true,
    showNext: true,
    id: "",
    title: "",
    uuid: "", //当前正在阅读的uuid
    currentIndex: 0,
    content: "",
    show: false,
    readPage: 0,
    intercept: false,
    colorList: [{
      color: "#151515",
      bgc: "#d7e6dc",
      borderColor:"#ccc"
    }, {
      color: "#151515",
      bgc: "#eae6dc",
      borderColor:"#ccc"
    }, {
      color: "#151515",
      bgc: "#e8b97a",
      borderColor:"#ccc"
    }, {
      color: "#ccc",
      bgc: "#000000",
      borderColor:"#ccc"
    }, ],
    active: 0,
    options: {
      offsetFontSize: 0,
      color: "#151515",
      backgroundColor: "#d7e6dc",
      borderColor:"#ccc",
      model: 0
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  //样式相关
  changeBgc(evt) {
    let {
      item,
      index
    } = evt.target.dataset;
    if (!item) return;
    this.setData({
      options: {
        ...this.data.options,
        backgroundColor: item.bgc,
        color: item.color,
        borderColor:item.borderColor
      },
      active: index
    });
    wx.setStorageSync('readStyle', this.data.options);
  },
  changeFont(evt) {
    let {
      offsetfontsize
    } = evt.target.dataset;
    if (!offsetfontsize) return;
    let size = parseInt(offsetfontsize);
    if (Math.abs(this.data.options.offsetFontSize + size) > 10) {
      wx.showToast({
        title: '极限了',
        icon: "error"
      });
      return;
    }
    this.setData({
      options: {
        ...this.data.options,
        offsetFontSize: this.data.options.offsetFontSize + size
      }
    });
    wx.setStorageSync('readStyle', this.data.options);
  },
  //拦截
  checkIntercept() {
    if (this.data.intercept) {
      return false;
    } else {
      this.setData({
        intercept: true
      });
      return true;
    }
  },
  //切换章节
  nextPage() {
    if (!this.checkIntercept()) return;
    console.log("next");
    let readPage = this.data.readPage;
    if (!app.globalData.chapterList[readPage + 1]) {
      wx.showToast({
        title: '已经是最后一章了',
        icon: "error"
      });
      this.setData({
        intercept: false
      });
      return;
    }
    if (app.globalData.chapterList[readPage + 1].needPay) {
      wx.showToast({
        title: '下一章请购买',
        icon: "error"
      });
      this.setData({
        intercept: false
      });
      return;
    } else {
      readPage += 1;
      this.setData({
        readPage,
        uuid: app.globalData.chapterList[readPage].uuid
      });
      this.getPageContent(readPage);
    }
  },
  lastPage() {
    if (!this.checkIntercept()) return;
    console.log("last");
    let readPage = this.data.readPage;
    if (!app.globalData.chapterList[readPage - 1]) {
      wx.showToast({
        title: '已经是第一章了',
        icon: "error"
      });
      this.setData({
        intercept: false
      });
      return;
    }
    if (app.globalData.chapterList[readPage - 1].neepPay) {
      wx.showToast({
        title: '上一章节还没有免费开放',
        icon: "error"
      });
      return;
    } else {
      readPage -= 1;
      this.setData({
        readPage,
        uuid: app.globalData.chapterList[readPage].uuid
      });
      this.getPageContent(readPage);
    }
  },
  async getPageContent(readPage, downloadNext = false) {
    let uuid = this.data.uuid;
    if (downloadNext) {
      if (app.globalData.chapterList[readPage]?.needPay) return;
      uuid = app.globalData.chapterList[readPage]?.uuid;
    }
    if (this.data.catcheList[readPage]?.page && this.data.catcheList[readPage]?.page == readPage && !downloadNext) {
      this.setData({
        readPage,
        content: this.data.catcheList[readPage]?.content,
        top: 0,
        intercept: false
      });
      let list = wx.getStorageSync('read') || [];
      list = [{
        ...app.globalData.bookInfo,
        readPage
      }, ...list.filter(el => el.id != app.globalData.bookInfo.id)]
      wx.setStorageSync('read', list);
      this.getPageContent((readPage + 1), true);
      return;
    }
    if (!downloadNext) {
      wx.showLoading();
      let list = wx.getStorageSync('read') || [];
      list = [{
        ...app.globalData.bookInfo,
        readPage
      }, ...list.filter(el => el.id != app.globalData.bookInfo.id)]
      wx.setStorageSync('read', list);
      this.getPageContent((readPage + 1), true);
    }
    let type = "update";
    const _ = db.command;
    let res = await db.collection(chapterContent).where({
      id: this.data.id
    }).get();
    if (!res.data.length) {
      type = "set";
    }
    db.collection(chapterContent).where({
      id: this.data.id,
      "list.uuid": uuid
    }).get().then(res => {
      if (res.data?.length) {
        let content = res.data[0].list.filter(el => el.uuid == uuid)[0].content;
        if (!downloadNext) {
          this.setData({
            content,
            top: 0,
            intercept: false
          });
        }
        this.setData({
          [`catcheList[${readPage}]`]: {
            page: readPage,
            content
          }
        });
        wx.hideLoading();
      } else {
        wx.request({
          url: `${app.globalData.baseUrlData}/yunyuedu/reader/book/content.json?source_uuid=${this.data.id}&content_uuid=${uuid}`,
          method: "GET",
          success: res => {
            let content = res.data.data.content;
            if (!downloadNext) {
              this.setData({
                content,
                top: 0,
                intercept: false
              });
              wx.hideLoading();
            }
            this.setData({
              [`catcheList[${readPage}]`]: {
                page: readPage,
                content
              }
            });
            wx.cloud.callFunction({
              name: "changeChapterContent",
              data: {
                id: this.data.id,
                uuid: uuid,
                content,
                type
              }
            })
          },
          fail: err => {
            wx.hideLoading();
            wx.showToast({
              title: '该章节出现问题',
              icon: "error"
            });
          }
        });
      }
    });
  },
  async onLoad(options) {
    let uuid = options?.uuid;
    let list = wx.getStorageSync('read') || [];
    let readPage = list.filter(el => el.id == options.id)[0]?.readPage;
    if (!readPage) {
      readPage = 0;
      uuid = app.globalData.chapterList[0].uuid
    } else {
      uuid = app.globalData.chapterList[readPage].uuid
    }
    this.setData({
      id: options.id,
      title: options.title,
      uuid,
      readPage
    });
    list = [{
      ...app.globalData.bookInfo,
      readPage
    }, ...list.filter(el => el.id != options.id)]
    wx.setStorageSync('read', list);
    this.getPageContent(readPage);
  },

  // 补0
  getZero(time) {
    return time > 10 ? time : '0' + time
  },

  // 弹出层
  popupShow() {
    this.setData({
      show: true
    })
  },

  // 关闭弹出层
  onClose() {
    this.setData({
      show: false
    })
  },

  toChapter() {
    wx.navigateTo({
      url: '/pages/chapter/chapter',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  // 对content进行切割处理

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let readStyle = wx.getStorageSync('readStyle');
    console.log("reads",readStyle);
    if (readStyle) {
      this.setData({
        options:readStyle
      })
    }
    let book = app.globalData.bookInfo;
    if (!book) {
      return
    }
    db.collection('readHistory').where({
      id: this.data.id
    }).get().then((res) => {
      if (!res.data.length) {
        db.collection('readHistory').add({
          data: {
            book,
            id: this.data.id,
            readTime: this.getZero(new Date().getMonth() + 1) + '月' + this.getZero(new Date().getDate()) + '号' + this.getZero(new Date().getHours()) + ':' + this.getZero(new Date().getMinutes())
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})